package com.mulanweb.api.module.controller.wechat;

import com.mulanweb.api.module.controller.BaseController;
import com.mulanweb.api.module.model.*;
import com.mulanweb.handler.CouponHandler;
import com.mulanweb.handler.wechat.PaymentSeller;
import com.mulanweb.handler.wechat.SentModelMessageHandler;
/**
 * Created by Administrator on 2016/11/8 0008.
 */
public class RefundController extends BaseController{

    public void applyRefund() {
        String openId = super.getSessionAttr("openId");
        //String openId = "oULNBwOvt_D2A_8se1bQOQ06ky0w";
        String orderNumber = getPara("orderNumber");//"XXL33148041036821015";//
        Order order = Order.dao.findFirst("SELECT * FROM `order` WHERE order_number=?",orderNumber);
        if(order !=null){
            User user = User.dao.findById(order.getUserId());
            if(user !=null){
                Long statusId = order.getStatusId();
                Float couponValue = 0F ;
                Coupon coupon = Coupon.dao.findById(order.getCouponId());
                if(coupon !=null){
                    couponValue = coupon.getValue();
                }
                if(statusId == 4 && user.getOpenId().equals(openId)){
                    try {
                        if(PaymentSeller.refundToUser(order.getOrderNumber(), (order.getAmount()*order.getUnitPrice()) - couponValue) ){
                            if(order.getTypeId() == 23){
                                Ticket ticket = Ticket.dao.findById(order.getTargetId());
                                ticket.setSurplusTotal(ticket.getSurplusTotal()+order.getAmount());
                                ticket.update();
                            }
                            //用户执行退款操作，优惠券使用次数恢复
                            CouponHandler.cancelCoupon(order.getId());
                            returnSuccessJson();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }else{
                returnFailureJson();
            }
        }
    }
}
